﻿using System.Diagnostics.CodeAnalysis;
using System.Net;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;

namespace Devonline.AspNetCore;

/// <summary>
/// 基于 HttpClient 
/// </summary>
/// <typeparam name="TEndpoint"></typeparam>
/// <param name="logger"></param>
/// <param name="httpClientFactory"></param>
/// <param name="endpoint"></param>
public class HttpClientResultService<TEndpoint>(
    ILogger<HttpClientResultService<TEndpoint>> logger,
    IHttpClientFactory httpClientFactory,
    TEndpoint endpoint
    ) : HttpClientService<TEndpoint>(logger, httpClientFactory, endpoint)
    where TEndpoint : IEndpoint
{
    /// <summary>
    /// 使用 HTTP 方法调用接口后处理返回值为 HttpResult<TResponseModel> 结构的结果
    /// </summary>
    /// <typeparam name="TResponseModel">HTTP 返回值类型</typeparam>
    /// <param name="content">HTTP 返回值原内容</param>
    /// <param name="path">接口地址, 不传值默认使用当前 endpoint 的 Path 值</param>
    /// <param name="desc">接口描述, 不传值默认使用当前 endpoint 的 Doc 值</param>
    /// <returns></returns>
    /// <exception cref="BadHttpRequestException"></exception>
    protected override TResponseModel? ResponseAdapter<TResponseModel>([DisallowNull] string content, string? path = null, string? desc = null) where TResponseModel : default
    {
        if (string.IsNullOrWhiteSpace(content))
        {
            _logger.LogInformation($"{_userAccess}: call interface {desc} success, but not return data, now will back to the call point");
            return default;
        }

        var httpResult = content.ToJsonObject<HttpResult<TResponseModel>>();
        if (httpResult is null)
        {
            _logger.LogWarning($"{_userAccess}: call interface {desc} success, but return data can not serialized, please check the return data!");
            throw new BadHttpRequestException($"调用 {desc} 接口失败, 失败原因: 返回结果无法反序列化");
        }

        if (httpResult.Code != (int)HttpStatusCode.OK)
        {
            _logger.LogWarning($"{_userAccess}: call interface {desc} success, but result data failed, the result code: {httpResult.Code}, message: {httpResult.Message}");
            throw new BadHttpRequestException($"调用 {desc} 接口失败, 失败原因: {httpResult.Message}");
        }

        _logger.LogInformation($"{_userAccess}: call interface {desc} success, and return data serialize success, now will back the result to the call point");
        return httpResult.Data;
    }
}